﻿using _698._45Tool.Utils;
using CommonServiceLocator;
using Communication;
using DocumentFormat.OpenXml.Spreadsheet;
using GalaSoft.MvvmLight.Messaging;
using Jn698._45GWTool.Models;
using Jn698._45GWTool.ServiceReference1;
using Jn698._45GWTool.Services;
using Jn698._45GWTool.Settings;
using Jn698._45GWTool.ViewModels;
using Jn698._45Tool.Utils;
using nblTool.utils;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.ServiceModel;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using WebFirst.Entities;
using static Communication.MessageGenerationModule;

namespace Jn698._45GWTool.Communication
{
    public class SendModule
    {
        private static readonly SendModule instance = new SendModule();
        public static SendModule Instance { get; } = instance;
        
        
        private SerialPortHelper serialPortHelper = SerialPortHelper.Instance;
        private TcpHelper tcpHelper = TcpHelper.Instance;

        public static int SecuritySelectedIndex = 0;

        public CancellationTokenSource cts = null;
        public Task MainTask = null;

        private GWCmdMakeUp gWCmdMakeUpSelected;
        public static string ESAMDiv;
        public static string ESAMVersion;
        public static string ESAMCounter;
        public static string SessionInit;
        public static string Sign;
        public static string RandHost;
        public static string SessionInitKey;
        public static string MasterCert;
        public static string TerminalCert;
        public static string cOutRandHost = "";
        public static int iKeyState;






       
       /* public void ReadRequest(ReadMode mode, List<string> OADSeleced, string DeviceAddress, int SecuritySelected)
        {

            //ReadMode mode = (ReadMode)RequestMode;
            if (mode == ReadMode.GetRequestNormal|| mode == ReadMode.GetRequestNext)
            {
                cts = new CancellationTokenSource();
                MainTask = Task.Run(async () =>
                {
                    foreach (var OAD in OADSeleced)
                    {
                        if (cts.Token.IsCancellationRequested)
                        {
                            Messenger.Default.Send<string>($"通讯停止({DateTime.Now.ToString()})\r\n", "StopMessage");
                            break;
                        }

                        while (true)
                        {
                            byte[] b = MessageGeneration(DeviceAddress, mode, OAD, SecuritySelected);
                            sendMessageShow(b);
                            //serialPortHelper.SendDataMethod(b);
                            //bool result = false;
                            //await Task.Run(() => result = serialPortHelper.DataReceiveFunction());
                            //await sendMessageAsync(DeviceAddress, b);
                            switch (CommViewModel.selectedCommType)
                            {
                                case "串口":
                                    serialPortHelper.SendDataMethod(b);
                                    bool result = false;
                                    await Task.Run(() => result = serialPortHelper.DataReceiveFunction());

                                    break;
                                case "GPRS":

                                    tcpHelper.isComplete = false;
                                    tcpHelper.SendData(DeviceAddress, b);
                                    await awitTCPRecv(5);

                                    break;
                                default:
                                    break;
                            }
                            */
       /*while (AnalysisMessage.lastblock == 0)
                            {
                                ReadRequest(ReadMode.GetRequestNext, new List<string>() { AnalysisMessage.block.ToString("X4") }, MainViewModel.selectedDevice.DeviceAddress, 0);
                            }*/
       /*
                            //Console.WriteLine(result);
                            break;
                        }

                    }
                }, cts.Token);

            }
            else if (mode == ReadMode.GetRequestNormalList)
            {
                MainTask = Task.Run(async () =>
                {
                    string OADs = "";
                    foreach (var OAD in OADSeleced)
                    {
                        OADs += OAD;
                    }
                    byte[] b = MessageGeneration(DeviceAddress, mode, OADs, SecuritySelected);
                    sendMessageShow(b);
                    //bool result = false;
                    await sendMessageAsync(DeviceAddress, b);

                });

            }
        }*/
        public void ReadRequest(ReadMode mode, List<BatchParaConfig> OADSeleced, string DeviceAddress)
        {

            //ReadMode mode = (ReadMode)RequestMode;
            if (mode == ReadMode.GetRequestNormal)
            {
                cts = new CancellationTokenSource();
                MainTask = Task.Run(async () =>
                {
                    foreach (var OAD in OADSeleced)
                    {
                        if (cts.Token.IsCancellationRequested)
                        {
                            Messenger.Default.Send<string>($"通讯停止({DateTime.Now.ToString()})\r\n", "StopMessage");
                            break;
                        }

                        while (true)
                        {
                            SecuritySelectedIndex = OAD.ReadSecurity ?? 0;
                            byte[] b = MessageGeneration(DeviceAddress, mode, OAD.StrOAD, SecuritySelectedIndex);
                            sendMessageShow(b);
                            //serialPortHelper.SendDataMethod(b);
                            //bool result = false;
                            //await Task.Run(() => result = serialPortHelper.DataReceiveFunction());
                            //await sendMessageAsync(DeviceAddress, b);
                            switch (CommViewModel.selectedCommType)
                            {
                                case "串口":
                                    serialPortHelper.SendDataMethod(b);
                                    bool result = false;
                                    await Task.Run(() => result = serialPortHelper.DataReceiveFunction());

                                    break;
                                case "GPRS":

                                    tcpHelper.isComplete = false;
                                    tcpHelper.SendData(DeviceAddress, b);
                                    await awitTCPRecv(50);

                                    break;
                                default:
                                    break;
                            }
                            //Console.WriteLine(result);
                            break;
                        }

                    }
                }, cts.Token);

            }
            
        }

        public Task ReadRequest(ReadMode mode, List<string> OADSeleced, string DeviceAddress, int SecuritySelected)
        {

            //ReadMode mode = (ReadMode)RequestMode;
            if (mode == ReadMode.GetRequestNormal || mode == ReadMode.GetRequestNext)
            {
                cts = new CancellationTokenSource();
                MainTask = Task.Run(async () =>
                {
                    foreach (var OAD in OADSeleced)
                    {
                        if (cts.Token.IsCancellationRequested)
                        {
                            Messenger.Default.Send<string>($"通讯停止({DateTime.Now.ToString()})\r\n", "StopMessage");
                            break;
                        }

                        while (true)
                        {
                            byte[] b = MessageGeneration(DeviceAddress, mode, OAD, SecuritySelected);
                            sendMessageShow(b);
                            //serialPortHelper.SendDataMethod(b);
                            //bool result = false;
                            //await Task.Run(() => result = serialPortHelper.DataReceiveFunction());
                            //await sendMessageAsync(DeviceAddress, b);
                            switch (CommViewModel.selectedCommType)
                            {
                                case "串口":
                                    serialPortHelper.SendDataMethod(b);
                                    bool result = false;
                                    await Task.Run(() => result = serialPortHelper.DataReceiveFunction());

                                    break;
                                case "GPRS":

                                    tcpHelper.isComplete = false;
                                    tcpHelper.SendData(DeviceAddress, b);
                                    await awitTCPRecv(5);

                                    break;
                                default:
                                    break;
                            }
                            /*while (AnalysisMessage.lastblock == 0)
                            {
                                ReadRequest(ReadMode.GetRequestNext, new List<string>() { AnalysisMessage.block.ToString("X4") }, MainViewModel.selectedDevice.DeviceAddress, 0);
                            }*/
                            //Console.WriteLine(result);
                            break;
                        }

                    }
                }, cts.Token);

            }
            else if (mode == ReadMode.GetRequestNormalList)
            {
                MainTask = Task.Run(async () =>
                {
                    string OADs = "";
                    foreach (var OAD in OADSeleced)
                    {
                        OADs += OAD;
                    }
                    byte[] b = MessageGeneration(DeviceAddress, mode, OADs, SecuritySelected);
                    sendMessageShow(b);
                    //bool result = false;
                    await sendMessageAsync(DeviceAddress, b);

                });

            }
            return MainTask;
        }
        public Task SetRequest(SetMode mode,Dictionary<string, string> map, string DeviceAddress, int SecuritySelected)
        {
            //SetMode mode = (SetMode)RequestMode;
            if (mode == SetMode.SetRequestNormal)
            {
                cts = new CancellationTokenSource();
                MainTask = Task.Run(async () =>
                {
                    foreach (var item in map)
                    {
                        Dictionary<string, string> sendOADData = new Dictionary<string, string>
                        {
                            { item.Key, item.Value }
                        };
                        if (cts.Token.IsCancellationRequested)
                        {
                            Messenger.Default.Send<string>($"通讯停止({DateTime.Now.ToString()})\r\n", "StopMessage");
                            break;
                        }

                        while (true)
                        {
                            byte[] b = MessageGeneration(DeviceAddress, mode, sendOADData, SecuritySelected);
                            sendMessageShow(b);
                            /*serialPortHelper.SendDataMethod(b);
                            bool result = false;
                            await Task.Run(() => result = serialPortHelper.DataReceiveFunction());
                            Console.WriteLine(result);*/
                            //await sendMessageAsync(DeviceAddress, b);
                            switch (CommViewModel.selectedCommType)
                            {
                                case "串口":
                                    serialPortHelper.SendDataMethod(b);
                                    bool result = false;
                                    await Task.Run(() => result = serialPortHelper.DataReceiveFunction());

                                    break;
                                case "GPRS":

                                    tcpHelper.isComplete = false;
                                    tcpHelper.SendData(DeviceAddress, b);
                                    await awitTCPRecv(50);
                                    
                                    break;
                                default:
                                    break;
                            }
                            break;

                        }

                    }
                }, cts.Token);

            }
            else if (mode == SetMode.SetRequestNormalList)
            {
                MainTask = Task.Run(async () =>
                {
                    byte[] b = MessageGeneration(DeviceAddress, mode, map, SecuritySelected);
                    sendMessageShow(b);
                    //await sendMessageAsync(DeviceAddress, b);
                    switch (CommViewModel.selectedCommType)
                    {
                        case "串口":
                            serialPortHelper.SendDataMethod(b);
                            bool result = false;
                            await Task.Run(() => result = serialPortHelper.DataReceiveFunction());

                            break;
                        case "GPRS":

                            tcpHelper.isComplete = false;
                            tcpHelper.SendData(DeviceAddress, b);
                            await awitTCPRecv(5);

                            break;
                        default:
                            break;
                    }
                    /*serialPortHelper.SendDataMethod(b);
                    bool result = false;
                    await Task.Run(() => result = serialPortHelper.DataReceiveFunction());*/
                    //Console.WriteLine(result);
                });


            }
            else if (mode == SetMode.SetThenGetRequestNormalList)
            {

            }
            return MainTask;
        }
        public Task ActionRequest(ActionMode mode,Dictionary<string, string> map, string DeviceAddress, int SecuritySelected)
        {
            //ActionMode mode = (ActionMode)RequestMode;
            if (mode == ActionMode.ActionRequest)
            {
                cts = new CancellationTokenSource();
                MainTask = Task.Run(async () =>
                {
                    foreach (var item in map)
                    {
                        Dictionary<string, string> sendOADData = new Dictionary<string, string>
                        {
                            { item.Key, item.Value }
                        };
                        if (cts.Token.IsCancellationRequested)
                        {
                            Messenger.Default.Send<string>($"通讯停止({DateTime.Now.ToString()})\r\n", "StopMessage");
                            break;
                        }

                        while (true)
                        {
                            byte[] b = MessageGeneration(DeviceAddress, mode, sendOADData, SecuritySelected);
                            sendMessageShow(b);
                            //await sendMessageAsync(DeviceAddress, b);
                            switch (CommViewModel.selectedCommType)
                            {
                                case "串口":
                                    serialPortHelper.SendDataMethod(b);
                                    bool result = false;
                                    await Task.Run(() => result = serialPortHelper.DataReceiveFunction());

                                    break;
                                case "GPRS":

                                    tcpHelper.isComplete = false;
                                    tcpHelper.SendData(DeviceAddress, b);
                                    await awitTCPRecv(5);

                                    break;
                                default:
                                    break;
                            }
                            //serialPortHelper.SendDataMethod(b);
                            //bool result = false;
                            //await Task.Run(() => result = serialPortHelper.DataReceiveFunction());
                            //Console.WriteLine(result);
                            break;

                        }

                    }
                }, cts.Token);

            }
            else if (mode == ActionMode.ActionRequest)
            {
                MainTask = Task.Run(async () =>
                {
                    byte[] b = MessageGeneration(DeviceAddress, mode, map, SecuritySelected);
                    sendMessageShow(b);
                    //await sendMessageAsync(DeviceAddress, b);
                    switch (CommViewModel.selectedCommType)
                    {
                        case "串口":
                            serialPortHelper.SendDataMethod(b);
                            bool result = false;
                            await Task.Run(() => result = serialPortHelper.DataReceiveFunction());

                            break;
                        case "GPRS":

                            tcpHelper.isComplete = false;
                            tcpHelper.SendData(DeviceAddress, b);
                            await awitTCPRecv(5);

                            break;
                        default:
                            break;
                    }
                    /*serialPortHelper.SendDataMethod(b);
                    bool result = false;
                    await Task.Run(() => result = serialPortHelper.DataReceiveFunction());
                    Console.WriteLine(result);*/
                });

            }
            else if (mode == ActionMode.ActionThenGetRequestNormalList)
            {

            }
            return MainTask;
        }

        public async Task FramingTask(string DeviceAddress, byte[] Data, int SecuritySelected)
        {
            await Task.Run(async() =>
            {
                int num = Data.Length%1024==0? Data.Length/1024: Data.Length/1024+1;
                bool result_flag = false;
                Enums.FramingEnum framingEnum=Enums.FramingEnum.Start;
                for (ushort i = 0; i < num; i++)
                {
                    var data = Data.Length > 1024 ? Data.Take(1024).ToArray() : Data;
                    if (i==0)
                    {
                        framingEnum = Enums.FramingEnum.Start;
                    }
                    else if (i+1==num)
                    {
                        framingEnum = Enums.FramingEnum.Middle;
                    }
                    else
                    {
                        framingEnum = Enums.FramingEnum.End;
                    }
                    var b = MessageGeneration(DeviceAddress, framingEnum, i, data, SecuritySelected);
                    Messenger.Default.Send<string>($"发送帧({DateTime.Now.ToString()})：{string.Join(" ", b.Select(x => x.ToString("X2")))}", "SendMessage");
                    switch (CommViewModel.selectedCommType)
                    {
                        case "串口":
                            serialPortHelper.SendDataMethod(b);
                            await Task.Run(() => result_flag = serialPortHelper.DataReceiveFunction(), cts.Token);
                            break;
                        case "GPRS":
                            tcpHelper.isComplete = false;
                            tcpHelper.SendData(MainViewModel.selectedDevice.DeviceAddress, b);
                            //await awitTCPRecv(5, new CancellationTokenSource().Token);
                            await awitTCPRecv(5);
                            result_flag = tcpHelper.isComplete;
                            break;
                        default:
                            break;
                    }
                    if (result_flag == false)
                    {
                        break;
                    }
                    //下发成功
                    if (Data.Length > 1024)
                    {
                        Data = Data.Skip(1024).ToArray();
                    }
                }
            });
        }

        public Task Connect(string DeviceAddress,string DataValue)
        {
            StateGridClient sc = ServiceLocator.Current.GetInstance<MainViewModel>().sc;
            ServiceLocator.Current.GetInstance<MainViewModel>().ConnectFlag = false;
            cts = new CancellationTokenSource();
            MainTask = Task.Run(async () =>
            {
                string data = "";
                SessionInit = "";
                Sign = "";
                SessionInitKey = "";

                string cOutSessionInit = "";
                string cOutSign;
                if (string.IsNullOrWhiteSpace(ESAMDiv) || string.IsNullOrWhiteSpace(ESAMCounter))
                {
                    MessageBox.Show("请先获取ESAM信息");
                    return;
                }
                try
                {

                    if (sc.State == CommunicationState.Closed)
                    {
                        /*Config config = XmlHelper.Deserializer<Config>("Config.xml");
                        try
                        {
                            if (config != null)
                            {
                                System.ServiceModel.Channels.Binding binding = new NetTcpBinding(SecurityMode.None, true);
                                //EndpointAddress endpoint = new EndpointAddress("net.tcp://10.1.2.32:10010/StateGrid/");
                                EndpointAddress endpoint = new EndpointAddress(config.EndpointAddress);
                                sc = new StateGridClient(binding, endpoint);
                            }
                            else
                            {
                                MessageBox.Show("获取加密机服务地址错误,请检查配置文件是否正确");
                            }
                        }
                        catch (Exception)
                        {
                            MessageBox.Show("获取加密机服务地址错误,请检查配置文件是否正确");
                        }*/
                        System.ServiceModel.Channels.Binding binding = new NetTcpBinding(SecurityMode.None, true);
                        //EndpointAddress endpoint = new EndpointAddress("net.tcp://10.1.2.32:10010/StateGrid/");
                        //EndpointAddress endpoint = new EndpointAddress(config.EndpointAddress);
                        EndpointAddress endpoint = new EndpointAddress(EncryptorSettings.Instanse.EndpointAddress);
                        sc = new StateGridClient(binding, endpoint);
                        ServiceLocator.Current.GetInstance<MainViewModel>().sc = sc;
                    }
                    //string cOutRandHost = "";
                    int r = 0;
                    string authenticationFlag = "";
                    string Counter = (Convert.ToInt64(ESAMCounter) + 1).ToString("X8");
                    iKeyState = 0;
                    if (ESAMVersion.Contains("7FFFFFFFF"))
                    {
                        iKeyState = 1;
                    }

                    if (MainViewModel.selectedDevice.DeviceType.Equals("集中器"))
                    {
                        if (string.IsNullOrWhiteSpace(MasterCert))
                        {
                            ReadRequest(ReadMode.GetRequestNormal, new List<string> { "F1000C00" }, DeviceAddress,0);
                            Thread.Sleep(1000);
                            if (string.IsNullOrWhiteSpace(MasterCert))
                            {
                                MessageBox.Show("获取证书失败");
                                return;
                            }
                        }
                        authenticationFlag = "03";
                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：请求加密机服务中...", "Info");
                        r = sc.Obj_Terminal_Formal_InitSession(iKeyState, ESAMDiv, Counter, "01", MasterCert, out cOutRandHost, out cOutSessionInit, out cOutSign);
                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：请求加密机服务完成", "Info");
                    }
                    else
                    {
                        authenticationFlag = "02";
                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：请求加密机服务中...", "Info");
                        r = sc.Obj_Meter_Formal_InitSession(iKeyState, ESAMDiv, Counter, "01", out cOutRandHost, out cOutSessionInit, out cOutSign);
                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：请求加密机服务完成", "Info");
                    }
                    //sc.Obj_Terminal_Formal_GetCACertificateData(iKeyState, ESAMDiv, Counter, "01");
                    //r = sc.Obj_Meter_Formal_InitSession(iKeyState, ESAMDiv, Counter, "01", out string cOutRandHost, out string cOutSessionInit, out string cOutSign);
                    //r = sc.Obj_Terminal_Formal_InitSession(iKeyState, ESAMDiv, Counter, "01", MasterCert, out string cOutRandHost, out string cOutSessionInit, out string cOutSign);
                    if (r == 0)
                    {
                        
                        var strings = DataValue.Split(';');
                        if (strings.Length<8)
                        {
                            MessageBox.Show("参数错误");
                            return;
                        }
                        data += strings[0].PadLeft(4, '0');
                        data += strings[1].PadRight(16, '0');
                        data += strings[2].PadRight(32, '0');
                        data += Convert.ToInt16(strings[3]).ToString("X4");
                        data += Convert.ToInt16(strings[4]).ToString("X4");
                        data += strings[5].PadLeft(2, '0');
                        data += Convert.ToInt16(strings[6]).ToString("X4");
                        data += Convert.ToInt32(strings[7]).ToString("X8");
                        //data += Convert.ToByte(strings[8]).ToString("X2");
                        data += authenticationFlag;
                        data += ((cOutSessionInit.Length / 2).ToString("X2") + cOutSessionInit + (cOutSign.Length / 2).ToString("X2") + cOutSign);
                        byte[] b = MessageGeneration(ConnectMode.Connect, DeviceAddress, data, 0);
                        sendMessageShow(b);
                        switch (CommViewModel.selectedCommType)
                        {
                            case "串口":
                                serialPortHelper.SendDataMethod(b);
                                bool result = false;
                                await Task.Run(() => result = serialPortHelper.DataReceiveFunction());
                                if (result)
                                {
                                    if (string.IsNullOrWhiteSpace(SessionInit) || string.IsNullOrWhiteSpace(Sign))
                                    {
                                        //MessageBox.Show("获取应用连接数据失败");
                                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：获取应用连接数据失败", "Info");
                                        return;
                                    }
                                    Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：请求加密机服务中...", "Info");
                                    r = sc.Obj_Meter_Formal_VerifySession(iKeyState, ESAMDiv, cOutRandHost, SessionInit, Sign, out SessionInitKey);
                                    Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：请求加密机服务完成", "Info");
                                    if (r == 0)
                                    {
                                        ServiceLocator.Current.GetInstance<MainViewModel>().ConnectFlag = true;
                                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：连接成功", "Info");
                                        //MessageBox.Show("连接成功");
                                    }
                                    else
                                    {
                                        //MessageBox.Show($"获取加密数据失败，错误码：{r}");
                                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：获取加密数据失败，错误码：{r}", "Info");
                                    }
                                }
                                break;
                            case "GPRS":
                                tcpHelper.isComplete = false;
                                tcpHelper.SendData(DeviceAddress, b);
                                //await Task.Delay(1000);
                                await awitTCPRecv(5);
                                if (tcpHelper.isComplete == true)
                                {
                                    if (string.IsNullOrWhiteSpace(SessionInit) || string.IsNullOrWhiteSpace(Sign))
                                    {
                                        //MessageBox.Show("获取应用连接数据失败");
                                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：获取应用连接数据失败", "Info");
                                        return;
                                    }
                                    Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：请求加密机服务中...", "Info");
                                    r = sc.Obj_Terminal_Formal_VerifySession(iKeyState, ESAMDiv, cOutRandHost, SessionInit, Sign, TerminalCert, out SessionInitKey);
                                    Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：请求加密机服务完成", "Info");
                                    if (r == 0)
                                    {
                                        ServiceLocator.Current.GetInstance<MainViewModel>().ConnectFlag = true;
                                        //MessageBox.Show("连接成功");
                                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：连接成功", "Info");
                                    }
                                    else
                                    {

                                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：获取加密数据失败，错误码：{r}", "Info");
                                    }
                                }
                                break;
                            default:
                                break;
                        }

                    }
                    else
                    {
                        //MessageBox.Show($"获取加密数据失败，错误码：{r}");
                        Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：获取加密数据失败，错误码：{r}", "Info");
                    }
                }
                catch (Exception e1)
                {
                    Messenger.Default.Send<string>($"({DateTime.Now.ToString()})：请求加密机服务失败，服务器无响应,错误信息：{e1.Message}", "Info");
                    sc.Close();

                    return;
                }

            }, cts.Token);
            return MainTask;
        }
        public void DisConnect(string DeviceAddress)
        {
            cts = new CancellationTokenSource();
            MainTask = Task.Run(async () =>
            {

                try
                {
                    byte[] b = MessageGeneration(ConnectMode.DisConnect, DeviceAddress, "", 0);
                    sendMessageShow(b);
                    switch (CommViewModel.selectedCommType)
                    {
                        case "串口":
                            serialPortHelper.SendDataMethod(b);
                            bool result = false;
                            await Task.Run(() => result = serialPortHelper.DataReceiveFunction());
                            if (result == true)
                            {
                                ServiceLocator.Current.GetInstance<MainViewModel>().ConnectFlag = false;
                            }
                            break;
                        case "GPRS":

                            tcpHelper.isComplete = false;
                            tcpHelper.SendData(DeviceAddress, b);
                            await awitTCPRecv(5);
                            if (tcpHelper.isComplete == true)
                            {
                                ServiceLocator.Current.GetInstance<MainViewModel>().ConnectFlag = false;
                            }
                            break;
                        default:
                            break;
                    }

                }
                catch (Exception e1)
                {

                    MessageBox.Show(e1.Message);
                    return;
                }

            }, cts.Token);
        }
        /// <summary>
        /// 发送帧显示
        /// </summary>
        /// <param name="b"></param>
        private void sendMessageShow(byte[] b)
        {
            string msgStr = "";
            for (int i = 0; i < b.Length; i++)
            {
                msgStr += b[i].ToString("X2") + " ";
            }
            Messenger.Default.Send<string>($"发送帧({DateTime.Now.ToString()})：{msgStr}", "SendMessage");
        }
        private async Task sendMessageAsync(string address, byte[] b)
        {
            switch (CommViewModel.selectedCommType)
            {
                case "串口":
                    serialPortHelper.SendDataMethod(b);
                    await Task.Run(() => serialPortHelper.DataReceiveFunction());
                    break;
                case "GPRS":
                    tcpHelper.SendData(address, b);
                    break;
                default:
                    break;
            }
        }

        private async Task awitTCPRecv(int timeOutSec)
        {
            using (var tokenSource = new CancellationTokenSource())
            {

                var startTime = DateTime.Now;
                while (true)
                {
                    if ((DateTime.Now - startTime) >= TimeSpan.FromSeconds(timeOutSec))
                    {
                        tokenSource.Cancel();
                    }
                    if (cts.IsCancellationRequested)
                    {
                        return;
                    }
                    if (tcpHelper.isComplete == true)
                    {
                        return;
                    }
                    await Task.Delay(TimeSpan.FromMilliseconds(10));
                }
            }
        }
    }
}
